<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="tsx" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { addRole, updateRole } from '/@/api/system/role';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('角色名称'),
      required: true,
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'code',
      label: t('角色编码'),
      required: true,
      component: 'Input',
      colProps: { span: 24 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'RadioButtonGroup',
      defaultValue: 1,
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { span: 24 },
    },
    {
      label: t('备注'),
      field: 'remark',
      component: 'InputTextArea',
      colProps: { span: 24 },
    },
    {
      label: ' ',
      field: 'authList',
      slot: 'menu',
      component: 'Input',
      colProps: { span: 24 },
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增角色') : t('编辑角色')));

  async function handleSubmit() {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addRole(values);
        notification.success({
          message: t('新增角色'),
          description: t('成功'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await updateRole(values);
        notification.success({
          message: t('编辑角色'),
          description: t('成功'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
